<?php
/**
 * Date: 2024.8
 * Author: kahn
 * 支付第三方回调
 */
use JetBrains\PhpStorm\NoReturn;
use service\vip\payment\AlipayService;
use service\vip\OrderService;
use service\vip\payment\WxpayService;

class NotifyController extends \Yaf_Controller_Abstract{

    /**
     * 1. 客户端调用 https://open.weixin.qq.com/connect/oauth2/authorize?接口
     * 2. 微信收到消息后, 重定向到redirect_uri指向的服务器端接口, 服务器拿到code
     * 3. 服务器调用https://api.weixin.qq.com/sns/oauth2/access_token, 微信同步返回服务器openId
     * 4. 服务器携带openId, 重定向到客户端网页
     *注意: 需微信公众号配置授权回调域名
     * 微信获取openId重定向
     * 这个步骤可以让客户端去做, 直接给code, 调用vip/public/openId获取openId
     */
    public function openIdAction(): void
    {
        if(!isset($_GET['code']) or !isset($_GET['state']) ){
            \Log::info("makeOpenIdNotifyAction params error",$_GET);
            return;
        }
        $state=$_GET['state'];
        $code = $_GET['code'];
        $returnUrl = str_replace('STATE','',$state);
        $returnUrl = base64_decode($returnUrl);
        
        \Log::info("makeOpenId get STATE $state");
        $openId = WxpayService::getPublicOpenId($code);
        if($openId){
            $returnUrl = $returnUrl."&openId=$openId";
            header("location:$returnUrl");
        }else{
            \Log::info("makeOpenIdNotifyAction getOpenId error");
        }
    }

    /**
     * @desc 支付宝回调
     */
    #[NoReturn] public function alipayAction(): void
    {
        $res = (new AlipayService())->notify();
        if(!$res){
            die("fail");
        }
        list($sn, $price, $tradeno, $paidTime) = $res;

        $ret = OrderService::deal($sn, $price, $tradeno, $paidTime);
        if(!$ret) {
            die("fail");
        }

        die("success");
    }

    /**
     * 微信 H5 支付异步通知
     */
    #[NoReturn] public function wxpayAction(): void
    {
        //$failMsg = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        //$successMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

        $res = (new WxpayService())->notify();
        if(!$res){
            die(WxpayService::failedResponse());
        }
        list($sn, $price, $tradeno, $paidTime) = $res;

        $ret = OrderService::deal($sn, $price, $tradeno, $paidTime);
        if(!$ret) {
            die(WxpayService::failedResponse());
        }

        die(WxpayService::successResponse());
    }
}